package handler

import (
	"github.com/gin-gonic/gin"
	"img-text-mgr/model"
	"img-text-mgr/pck"
	"strconv"
)

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	var user model.User
	err := model.DB.Where("tel=?", tel).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg": "用户不存在"})
		return
	}
	if pck.Md5(user.Password) != pck.Md5(password) {
		c.JSON(200, gin.H{"code": 500, "msg": "密码错误"})
		return
	}
	token := pck.TokenHandler(int(user.ID))
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功", "data": user, "token": token})
}
func Info(c *gin.Context) {
	uid, _ := c.Get("uid")
	c.JSON(200, gin.H{"code": 200, "msg": "解密成功", "uid": uid})

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []model.Article
	err := model.DB.Offset(offset).Limit(size).Find(&data).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "data": data})
}
